<template>
  <n-card :bordered="false" class="proCard">
    <!--表单部分,可以动态创建表单-->
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <!--展示信息部分-->
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row:ListData) => row.equipmentId"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="showUserdrawer" style="margin-right: 10px">
          <!-- “+”号图标
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template> -->
          新建
        </n-button>
        <n-button type="primary" :disabled="isRowKeysEmpty" @click="batchDelete" style="margin-right: 10px"> 删除 </n-button>
        <n-button type="primary" :disabled="isRowKeysEmpty" @click="assignUserdrawer">下发人员</n-button>
      </template>
      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-drawer v-model:show="showdrawer" :width="600">
      <n-drawer-content :title="titledrawer" closable>
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="100"
          class="py-4"
        >
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="12" label="设备号" path="equipmentId">
              <n-input placeholder="请输入设备号" v-model:value="formParams.equipmentId" clearable="true" :disabled="editStatus" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="设备名" path="equipmentName">
              <n-input placeholder="请输入设备名" v-model:value="formParams.equipmentName" clearable="true" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="项目" path="project">
              <n-select
                v-model:value="formParams.project"
                placeholder="请选择项目"
                :options="selectProjectOptions"
                @update:value="handleSelectProject"
                clearable="true"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="设备组" path="equipmentGroup">
              <n-select
                v-model:value="formParams.equipmentGroup"
                placeholder="请选择设备组"
                :options="selectGroupOptions"
                :disabled="isSelectGroupDisabled"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="设备类型" path="Type">
              <n-select
                v-model:value="formParams.type"
                placeholder="请选择设备类型"
                :options="typeOptions"
              />
            </n-form-item-gi>
          </n-grid>
        </n-form>
        <template #footer>
          <n-button type="primary" @click="saveuserinfo"> 提交 </n-button>
        </template>
      </n-drawer-content>
    </n-drawer>

    <!--下发人员-->
    <ReleaseEmp :parentData="parentData" :show = "rlsdrawer" :key="componentKey"/>

    <!--阅览已下发人员-->
    <ReleasedEmplist :parentData="parentData1" :show = "rlseddrawer" :key="componentKey1"/>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, toRefs, computed } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { getTableList, getProjcetOptions, getGroupOptions, batchDelEquipment, createEquipment, getEditInit, updateEquipment } from '@/api/equipment/equipment_list';
  import { columns, ListData } from './columns_equipmentList';
  import { type FormRules } from 'naive-ui';
  import ReleaseEmp from './components/ReleaseEmp.vue';
  import ReleasedEmplist from './components/ReleasedEmplist.vue';

  const selectProjectOptions = ref([]);
  const selectGroupOptions = ref([]);
  const isSelectGroupDisabled = ref(true);

  const parentData = ref([]);
  const parentData1 = ref('');
  const componentKey = ref(0);
  const componentKey1 = ref(0);
  // 获取第一个下拉框的选项数据
  onMounted(async () => {
    try {
      const options = await getProjcetOptions();
      selectProjectOptions.value = options;
    } catch (error) {
      console.error('Failed to fetch project options:', error);
    }
  });
  // 获取第二个下拉框的选项数据
  async function fetchAndSetGroupOptions(params) {
    try {
      const options = await getGroupOptions(params);;
      selectGroupOptions.value = options;
    } catch (error) {
      console.error('Failed to fetch group options:', error);
    }
  }

  const schemas: FormSchema[] = [
    {
      field: 'selectProject',
      component: 'NSelect',
      label: '选择项目',
      componentProps: {
        clearable: false,
        placeholder: '请选择项目',
        options: selectProjectOptions,
        onUpdateValue: (e: any) => {
          console.log('selectProjectOptions', e);
          if (e === null) {
            // 如果第一个下拉框没有选项，则禁用第二个下拉框
            isSelectGroupDisabled.value = true;
          } else {
            // 否则启用第二个下拉框，并根据需要更新选项
            isSelectGroupDisabled.value = false;
            fetchAndSetGroupOptions({ selectProject: e });
          }
        },
      },
    },
    {
      field: 'selectGroup',
      component: 'NSelect',
      label: '选择设备组',
      componentProps: {
        clearable: true,
        disabled: isSelectGroupDisabled,
        placeholder: '请选择设备组',
        options: selectGroupOptions,
        onUpdateValue: (e: any) => {
          // console.log('selectGroupOptions', e);
        },
      },
    },
    {
      field: 'searchValue',
      component: 'NInput',
      label: '快速查询',
      componentProps: {
        placeholder: '设备名称',
        onInput: (e: any) => {
          // console.log('searchValue', e);
        },
      },
      rules: [{ required: false, message: '', trigger: ['blur'] }],
    },
  ];
  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '3 s:3 m:4 l:5 xl:6 2xl:7' },
    labelWidth: 90,
    schemas,
    showAdvancedButton: false,
  });

  const formRef: any = ref(null);
  const actionRef = ref();
  const showModal = ref(false);
  const rlsdrawer = ref(false);
  const rlseddrawer = ref(false);
  const formBtnLoading = ref(false);


  const showdrawer = ref(false);
  const titledrawer = ref('');
  const editStatus = ref(false);

  const rules: FormRules = {
    equipmentId: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入设备Id',
    },
    equipmentName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入设备名',
    },
    project: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择项目',
    },
    equipmentGroup: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择设备组',
    },
    type: {
      required: true,
      trigger: ['blur', 'input'],
      message: '设备类型',
    },
  };

  const formParams = reactive({
    equipmentId: '',
    equipmentName: '',
    project: '',
    equipmentGroup: '',
    type: '',
  });

  function showUserdrawer() {
    showdrawer.value = true;
    editStatus.value = false;
    titledrawer.value = '新建设备';
    formParams.equipmentId = '';
    formParams.equipmentName = '';
    formParams.project = '';
    formParams.equipmentGroup = '';
    formParams.type = '';
  }

  const typeOptions = reactive([
    {
      label: '入口',
      value: '0',
    },
    {
      label: '出口',
      value: '1',
    },
  ]);

  function handleSelectProject(value) {
    if (value === null) {
      // 如果第一个下拉框没有选项，则禁用第二个下拉框
      isSelectGroupDisabled.value = true;
      selectGroupOptions.value = [];
      formParams.equipmentGroup = '';
    } else {
      // 否则启用第二个下拉框，并根据需要更新选项
      console.log('projectid:', formParams.project);
      isSelectGroupDisabled.value = false;
      selectGroupOptions.value = [];
      formParams.equipmentGroup = '';
      fetchAndSetGroupOptions({ selectProject: value });
    }
  }

  function saveuserinfo() {
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      if (!errors) {
        if (titledrawer.value == '编辑设备') {
          // 编辑用户
          const params = formParams;
          params.type = getValueByLabel(params.type);
          await updateEquipment(params);
          window['$message'].success('编辑成功');
        } else {
          // 创建用户
          const params = formParams;
          await createEquipment(params);
          window['$message'].success('新建成功');
        }
        setTimeout(() => {
          showdrawer.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请输入完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  // 数据表格部分的actionColumn
  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '已下发人员信息',
            onClick: showRlsEmplist.bind(null, record),
            ifShow: () => {
              return true;
            },
            // auth: ['basic_list'],
          },
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            // auth: ['basic_list'],
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            // auth: ['basic_list'],
          },
        ],

      });
    },
  });

  // 加载数据表
  const loadDataTable = async (res) => {
    const data = await getTableList({ ...getFieldsValue(), ...res });
    console.log('loadDataTableRes:', data);
    return data;
  };

  //cdx：其他地方使用rowKeys，需要将其定义为一个响应式变量
  const rowKeys = ref([]);
  function onCheckedRow(rKeys) {
    console.log('选中的行数据', rKeys);
    rowKeys.value = rKeys;
    parentData.value = rKeys;
    console.log('rowKeys.value', rowKeys.value.length);

  }
 
  //cdx：控制删除按钮是否可以点击，计算选中数据list的length是否为0。奇怪的是，直接在组件绑定“rowKeys.value.length === 0”会报错，转换为计算属性即可
  const isRowKeysEmpty = computed(() => {
    return rowKeys.value.length === 0;
  });

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e) {
    console.log('新建信息：', formParams);
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('新建信息：', formParams);
        window['$message'].success('新建成功');
        setTimeout(() => {
          showModal.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }
  // 根据后端传回来的value值初始化label值
  function getLabelByValue(value) {
    const option = typeOptions.find((option) => option.value === value);
    return option ? option.label : null;
  }
  // 将type（有可能是value，也有可能是label）映射到value值
  function getValueByLabel(label) {
    const option = typeOptions.find((option) => option.label === label);
    return option ? option.value : label;
  }
  const editInitParams = ref({});
  // cdx：表格里面的编辑按钮对应的函数
  async function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    editInitParams.value = await getEditInit({ equipmentId: record.equipmentId });
    console.log('init parmas:', editInitParams.value);
    showdrawer.value = true;
    editStatus.value = true;
    titledrawer.value = '编辑设备';
    formParams.equipmentId = editInitParams.value.equipmentId;
    formParams.equipmentName = editInitParams.value.equipmentName;
    formParams.project = editInitParams.value.project;
    formParams.equipmentGroup = editInitParams.value.equipmentGroup;
    formParams.type = getLabelByValue(editInitParams.value.type);
  }

  async function handleDelete(record: Recordable) {
    console.log('单挑删除的数据', [record.userId]);
    try {
      const res = await batchDelEquipment({ delEquipmentList: [record.equipmentId] });
      window['$message'].info('点击了删除');
      reloadTable();
      // router.push({ path: '/redirect' + unref(route).fullPath });
      console.log('DelRes:', res);
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }
  // cdx：表格上方的批量删除按钮对应的函数
  async function batchDelete() {
    console.log('批量删除的数据2:', rowKeys.value);
    try {
      const res = await batchDelEquipment({ delEquipmentList: rowKeys.value });
      window['$message'].info('点击了删除');
      reloadTable();
      rowKeys.value = []; // 清空勾选中的rowKeys，使得表格上面删除按钮不可选
      // router.push({ path: '/redirect' + unref(route).fullPath });
      console.log('batchDelRes:', res);
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }

  // 下发人员弹窗
  const assignParams = reactive({
    equipmentId: '',
    equipmentName: '',
    project: '',
    equipmentGroup: '',
    type: '',
  });

  function assignUserdrawer() {
    rlsdrawer.value = true;
    toRefs(parentData);
    toRefs(rlsdrawer);
    componentKey.value++;
  }

  function showRlsEmplist(values: Recordable) {
    console.log(values);
    rlseddrawer.value = true;
    parentData1.value = values.equipmentId + ',' + values.equipmentName;
    toRefs(parentData1);
    toRefs(rlseddrawer);
    componentKey1.value++;
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
    reloadTable();
  }
</script>

<style lang="less" scoped></style>
